

#include <sysclk.h>

/// @cond 0
/**INDENT-OFF**/
#ifdef __cplusplus
extern "C" {
#endif


//#if defined(CONFIG_SYSCLK_DEFAULT_RETURNS_SLOW_OSC)

//#endif

/*void sysclk_set_prescalers(uint32_t ul_pres)
{
	pmc_mck_set_prescaler(ul_pres);
	SystemCoreClockUpdate();
}*/


/*void sysclk_set_source(uint32_t ul_src)
{
	switch (ul_src) {
	case SYSCLK_SRC_SLCK_RC:
	case SYSCLK_SRC_SLCK_XTAL:
	case SYSCLK_SRC_SLCK_BYPASS:
		pmc_mck_set_source(PMC_MCKR_CSS_SLOW_CLK);
		break;

	case SYSCLK_SRC_MAINCK_4M_RC:
	case SYSCLK_SRC_MAINCK_8M_RC:
	case SYSCLK_SRC_MAINCK_12M_RC:
	case SYSCLK_SRC_MAINCK_XTAL:
	case SYSCLK_SRC_MAINCK_BYPASS:
		pmc_mck_set_source(PMC_MCKR_CSS_MAIN_CLK);
		break;

	case SYSCLK_SRC_PLLACK:
		pmc_mck_set_source(PMC_MCKR_CSS_PLLA_CLK);
		break;

	case SYSCLK_SRC_UPLLCK:
		pmc_mck_set_source(PMC_MCKR_CSS_UPLL_CLK);
		break;
	}

	SystemCoreClockUpdate();
}*/


void sysclk_enable_usb(void)
{
	//Assert(CONFIG_USBCLK_DIV > 0);

        //pmc_enable_upll_clock();
        PMC->CKGR_UCKR = CKGR_UCKR_UPLLCOUNT(3) | CKGR_UCKR_UPLLEN;
	// Wait UTMI PLL Lock Status 
	while (!(PMC->PMC_SR & PMC_SR_LOCKU));
	
        PMC->PMC_USB = PMC_USB_USBS | PMC_USB_USBDIV(CONFIG_USBCLK_DIV - 1);//pmc_switch_udpck_to_upllck(CONFIG_USBCLK_DIV - 1);
	PMC->PMC_SCER = PMC_SCER_UOTGCLK;//pmc_enable_udpck();
}

void sysclk_disable_usb(void)
{
	pll_disable(1);
}

void sysclk_full_run(void)
{
    struct pll_config pllcfg;
  
    system_init_flash();
    
    pll_enable_source(CONFIG_PLL0_SOURCE);
    pll_config_defaults(&pllcfg, 0);
    pll_enable(&pllcfg, 0);
    pll_wait_for_lock(0);
    pmc_switch_mck_to_pllack(CONFIG_SYSCLK_PRES);
}

void sysclk_idle(void)
{
    system_init_flash();
    pmc_switch_mainck_to_fastrc(CKGR_MOR_MOSCRCF_4_MHz);
    pmc_switch_mck_to_mainck(PMC_PCK_PRES_CLK_1);
    
    pmc_disable_pllack();
}
                          

/*void sysclk_init(void)
{
    struct pll_config pllcfg;
        
    pll_enable_source(CONFIG_PLL0_SOURCE);
    sysclk_full_run();
}*/

#ifdef __cplusplus
}
#endif
/**INDENT-ON**/
/// @endcond
